import Qs from "qs";
import axios from "axios";
import storage from "@/utils/storage.js";
let baseUrl
if (process.env.NODE_ENV === 'development') {
  baseUrl = '//60.190.238.5:8080/advance';   //  正式环境
} else {
	baseUrl= '//60.190.238.5:8080/advance';  //  正式环境
}
export default class Request {
  config = {
    baseUrl: baseUrl,
    method: "GET",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
    },
    responseType: "json",
    custom: {},
    timeout: 30000,
  };
  /* 判断url是否为绝对路径 */
  static posUrl(url) {
    return /(http|https):\/\/([\w.]+\/?)\S*/.test(url);
  }

  static addQueryString(params) {
    let paramsData = "";
    Object.keys(params).forEach(function (key) {
      paramsData += key + "=" + encodeURIComponent(params[key]) + "&";
    });
    return paramsData.substring(0, paramsData.length - 1);
  }

  /**
   * @property {Function} request 请求拦截器
   * @property {Function} response 响应拦截器
   * @type {{request: Request.interceptor.request, response: Request.interceptor.response}}
   */
  interceptor = {
    /**
     * @param {Request~requestCallback} cb - 请求之前拦截,接收一个函数（config, cancel）=> {return config}。第一个参数为全局config,第二个参数为函数，调用则取消本次请求。
     */
    request: (cb) => {
      if (cb) {
        this.requestBeforeFun = cb;
      }
    },
    /**
     * @param {Request~responseCallback} cb 响应拦截器，对响应数据做点什么
     * @param {Request~responseErrCallback} ecb 响应拦截器，对响应错误做点什么
     */
    response: (cb, ecb) => {
      if (cb && ecb) {
        this.requestComFun = cb;
        this.requestComFail = ecb;
      }
    },
  };

  requestBeforeFun(config) {
    return config;
  }

  requestComFun(response) {
    return response;
  }

  requestComFail(response) {
    return response;
  }

  /**
   * 自定义验证器，如果返回true 则进入响应拦截器的响应成功函数(resolve)，否则进入响应拦截器的响应错误函数(reject)
   * @param { Number } statusCode - 请求响应体statusCode（只读）
   * @return { Boolean } 如果为true,则 resolve, 否则 reject
   */
  validateStatus(statusCode) {
    return statusCode === 200;
  }

  /**
   * @Function
   * @param {Request~setConfigCallback} f - 设置全局默认配置
   */
  setConfig(f) {
    this.config = f(this.config);
  }

  /**
   * @Function
   * @param {Object} options - 请求配置项
   * @prop {String} options.url - 请求路径
   * @prop {Object} options.data - 请求参数
   * @prop {Object} [options.responseType = config.responseType] [text|arraybuffer] - 响应的数据类型
   * @prop {Object} [options.headers = config.headers] - 请求header
   * @prop {Object} [options.method = config.method] - 请求方法
   * @returns {Promise<unknown>}
   */
  async request(options = {}) {
    options.baseUrl = this.config.baseUrl;
    options.url = options.url || "";
    options.data = options.data || {};
    options.data.openId = storage.get("openId") || "oynD1smFVtAG8IxPymDT1AvPTQuY";
    options.params = options.params || {};
    options.headers = options.headers || this.config.headers;
    options.method = options.method || this.config.method;
    options.custom = { ...this.config.custom, ...(options.custom || {}) };

    // 判断有没有 catch 方法
    options.noCatch = typeof options.noCatch == "undefined" ? true : false;

    // 是否加载 loading
    options.isLoading = typeof options.isLoading == "undefined" ? true : false;

    return new Promise((resolve, reject) => {
      let handleRe = {};

      handleRe = { ...this.requestBeforeFun(options) };
      const _config = { ...handleRe };

      let mergeUrl = Request.posUrl(_config.url)
        ? _config.url
        : _config.baseUrl + _config.url;
      if (JSON.stringify(_config.params) !== "{}") {
        const paramsH = Request.addQueryString(_config.params);
        mergeUrl +=
          mergeUrl.indexOf("?") === -1 ? `?${paramsH}` : `&${paramsH}`;
      }
      _config.url = mergeUrl;
      if (options.type === "json") {
      } else {
        // 序列化处理
        if (options.hasFile) {
        } else {
          _config.data = Qs.stringify(_config.data);
        }
      }
      axios(_config)
        .then((response) => {
          response.config = handleRe;
          if (this.validateStatus(response.status)) {
            // 成功
            response = this.requestComFun(response);
            resolve(response);
          } else {
            response = this.requestComFail(response);
            reject(response);
          }
        })
        .catch((err) => {
          let response = this.requestComFail(err);
          reject(response);
        });
    });
  }

  get(url, data, options = {}) {
    url = url + "?" + Qs.stringify(data);
    return this.request({
      url,
      method: "GET",
      ...options,
    });
  }

  post(url, data, options = {}) {
    return this.request({
      url,
      data,
      method: "POST",
      ...options,
    });
  }
  postJson(url, data, options = {}) {
    options.headers = {
      "Content-Type": "application/json;charset=UTF-8",
    };
    options.type = "json";
    return this.request({
      url,
      data,
      method: "POST",
      ...options,
    });
  }

  upload(url, data) {
    let options = {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    };
    return new Promise((resolve, reject) => {
      let mergeUrl = Request.posUrl(url)
        ? url
        : baseUrl + url;
      axios
        .post(mergeUrl, data)
        .then((response) => {
          if (this.validateStatus(response.status)) {
            // 成功
            response = this.requestComFun(response);
            resolve(response);
          } else {
            response = this.requestComFail(response);
            reject(response);
          }
        })
        .catch((err) => {
          let response = this.requestComFail(err);
          reject(response);
        });
    });
  }
}
